// 导入依赖的模块
yepjs.require("jquery");
yepjs.require("YBA.Common");
yepjs.require("YBA.Plugin.plugins");
yepjs.require("YBA.Data.User");
yepjs.require("YBA.Data.Terminal");
yepjs.require("YBA.Logic.Department.deptSelect");

// 用户管理 - 用户管理
yepjs.define("list", {

    NS: "YBA.Logic.User",

    field: function() {

        var Biz = {
            // 初始化事件
            init: function() {
                Biz.fn.getList(function (json) {

                    // 设置初始列表项目的数量，创建分页控件需要使用该数量
                    Biz.vars.totalNum = json.page.totalRecord;

                    for (var i in Biz.event) {
                        Biz.event[i]();
                    }
                });
            },
            //  公共变量
            vars: {
                // 模板列表
                tpl: (function(){
                    var tpl = {};
                    $("script[type='text/ysmart']").each(function(){
                        var t = $(this);
                        tpl[t.attr("data-name")] = t.html();
                    });
                    return tpl;
                })(),
                // 搜索字段
                searchVar: {
                	startPos: 1,
                    pageSize: 20,
                    departId: "",
                    mobile: "",
                    name: "",
                    username: ""
                },
                // 列表项目的总数量
                totalNum: 100,
                // 分页控件引用
                pageCtrl: null
            },
            // 页面元素
            el: {
                body: $("body"),
                jdepartId: $("#j-departId"),
                jmobile: $("#j-mobile"),
                jname: $("#j-name"),
                jusername: $("#j-username"),
                jpage: $("#j-page"),
                jlist: $("#j-list"),
                jtotalNum: $("#j-totalNum"),
                jaddUser: $("#j-addUser"),
                jtransferUser:$("#j-transferUser"),
                jallObj:$(".j-checkAll"),
                jdepartIdStr:$("#j-departIdStr")
            },
            // 功能函数集合
            fn: {
                // 读取终端列表
                getList: function (callback) {
                    YBA.Data.User.getUserList(Biz.vars.searchVar, function (json) {
                        if(json.code == 200) {
                        	json.loginUser = loginUser;
                        	Biz.fn.getUserSpace(function(data){
                        		json.loginUser.availableSpaceSize = data.availableSpaceSize;
                        		Biz.el.jlist.html(YBA.Common.ysmart(Biz.vars.tpl.list, json));
                                Biz.el.jtotalNum.html(json.page.totalRecord);

                                Biz.vars.pageCtrl && Biz.vars.pageCtrl.setTotalNum(json.page.totalRecord);
                        	});

                            callback && callback(json);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc});
                        }
                    });
                },
                // 表单验证
                formCheck: function(form,name) {

                	// 显示错误信息
                    var showError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.addClass("msg-error").removeClass('msg-tip');
                        msgTxt.html(msg);
                        msgDom.show();
                    };

                    // 隐藏错误信息
                    var hideError = function(obj, msg) {
                        var msgDom = obj.siblings('.message');
                        var msgTxt = msgDom.children('i')
                        msgDom.hide();
                        msgDom.addClass("msg-tip").removeClass('msg-error');
                        msgTxt.html(msg);
                    };

                    // 数据验证对象
                    var dataCheck = {
                        name:{
                            obj: form.find("[name='name']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入姓名");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,10)){
                                	showError(this.obj,"姓名最大10个字符长度");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入姓名");
                                    return true;
                                }
                            }
                        },
                        username: {
                            obj: form.find("[name='username']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入用户名");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,30)){
                                	showError(this.obj,"用户名过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入用户名");
                                    return true;
                                }
                            }
                        },
                        password: {
                            obj: form.find("[name='password']"),
                            fn: function() {
                                if (this.obj.length <= 0) {return true;};
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入密码");
                                    return false;
                                } else if(!YBA.Common.check.isPwd(val)){
                                	showError(this.obj,"至少六位的英文数字组合");
                                    return false;
                                } else if(YBA.Common.check.isHowLong(val,50)){
                                	showError(this.obj,"密码过长");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入密码");
                                    return true;
                                }
                            }
                        },
                        spaceSize: {
                            obj: form.find("[name='spaceSize']"),
                            fn: function() {
                            	if (this.obj.length <= 0) {return true;};
                                var val = this.obj.val();
                                var maxSize = this.obj.attr("data-maxSize");
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入空间大小");
                                    return false;
                                } else if(!YBA.Common.check.isNum(val,{"min":1,"decimals":0})){
                                	showError(this.obj,"请输入正整数");
                                    return false;
                                } else if(parseInt(maxSize) < parseInt(val)){
                                	showError(this.obj,"您可分配空间为"+maxSize+"G");
                                    return false;
                                } else {
                                    hideError(this.obj,"您可分配空间为"+maxSize+"G");
                                    return true;
                                }
                            }
                        },
                        mobile: {
                            obj: form.find("[name='mobile']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入手机号");
                                    return false;
                                } else if (!YBA.Common.check.isMobile(val)) {
                                    showError(this.obj,"手机号不合法");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入手机号");
                                    return true;
                                }
                            }
                        },
                        email: {
                            obj: form.find("[name='email']"),
                            fn: function() {
                                var val = this.obj.val();
                                if (YBA.Common.check.isNull(val)) {
                                    showError(this.obj,"请输入邮箱");
                                    return false;
                                } else if (!YBA.Common.check.isEmail(val)) {
                                    showError(this.obj,"邮箱不合法");
                                    return false;
                                } else {
                                    hideError(this.obj,"请输入邮箱");
                                    return true;
                                }
                            }
                        }
                    };

                    if (name && dataCheck[name]) {
                        return dataCheck[name].fn();
                    } else {
                        var errLen = 0;
                        for (var i in dataCheck) {
                            if (!dataCheck[i].fn()) {
                                errLen++;
                            }
                        }
                        if (errLen > 0) {
                            return false;
                        }
                        return true;
                    }
                },
                //用户批量转移
                userTransfer:function(data){
                    var popform = new YBA.Plugin.popform({
                        title:"用户批量转移",
                        className:"ui-dialog-userTransfer",
                        content:YBA.Common.ysmart(Biz.vars.tpl.transferTpl,data || {}),
                        width:450,
                        destroy:true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow:function(){
                            // 显示弹窗时要执行的回调函数
                        },
                        btns: [{
                            value: "确定",
                            className: "blue btn g-mr10",
                            fn: function () {
                                var form = popform.self.find("form");
                                var data = form.serialize();
                                YBA.Data.User.transferUser(data, function(json){
                                    if(json.code == 200) {
                                        YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                        popform.hide();
                                        Biz.fn.getList();
                                        Biz.el.jallObj.removeAttr('checked');
                                    }else{
                                        YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                    }
                                });
                            }
                        },{
                            value: "取消",
                            className: "red btn g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();

                    // 创建组织机构下拉框
                    var deptSelect = YBA.Logic.Department.deptSelect({
                        con: popform.self.find(".j-deptSelect"),
                        onchange: function(val, text){

                        }
                    });

                    return false;
                },
                //查看用户详情弹窗
                userInfo:function(data){
                    var popform = new YBA.Plugin.popform({
                        title:data.name+"的信息",
                        className:"ui-dialog-userInfo",
                        content:YBA.Common.ysmart(Biz.vars.tpl.userinfoTpl,data || {}),
                        width:674,
                        destroy:true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow:function(){
                            // 显示弹窗时要执行的回调函数
                        },
                        btns: [{
                            value: "确定",
                            className: "blue btn g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();
                },
                // 用户新增或修改弹窗
                userForm: function(data){
                    var popform = new YBA.Plugin.popform({
                        title: (!(data))?"新增用户":"修改用户",
                        className: "ui-dialog-addUser",
                        content: YBA.Common.ysmart(Biz.vars.tpl.userTpl, data || {} ),
                        width: 564,
                        destroy: true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow: function () {
                            // 显示弹窗时要执行的回调函数
                            var op = $(".form-group");
                            var form = $(".ui-dialog-form");
                            op.each(function() {
                                var t = $(this),
                                    input = t.find(".required"),
                                    name = input.attr("name"),
                                    holder = input.siblings(".message");
                                input.blur(function() {
                                    Biz.fn.formCheck(form,name);
                                }).focus(function() {
                                    holder.show();
                                });;
                            });
                            if(!data){
                            	Biz.fn.getUserSpace(function(json){
                            		$("#j-availableSpace").attr("data-maxSize",json.availableSpaceSize);
                            	})
                            	Biz.fn.getCaList($("#j-caId"));
                            }
                        },
                        btns: [{
                            value: "确定",
                            className: "blue btn g-mr10",
                            fn: function () {
                                var form = $(".ui-dialog-form");
                                if (!Biz.fn.formCheck(form)) {
                                    return false;
                                }else{
                                    var form = popform.self.find("form");
                                    var data = form.serialize();
                                    var dataId = $("#j-dataId").val();
                                    var callbackFn = function(json){
                                        if(json.code == 200) {
                                            YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                            popform.hide();
                                            Biz.fn.getList();
                                        }else{
                                            YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                        }
                                    }
                                    if(!dataId){
                                        YBA.Data.User.addUser(data, callbackFn);
                                    }else{
                                        YBA.Data.User.updateUser(data, callbackFn);
                                    }
                                }
                            }
                        }, {
                            value: "取消",
                            className: "red btn g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();

                    // 创建组织机构下拉框
                    var deptSelect = YBA.Logic.Department.deptSelect({
                        con: popform.self.find(".j-deptSelect"),
                        onchange: function(val, text){

                        }
                    });

                    return false;
                },
                // 追加空间弹窗
                addToSpaceForm: function(id){
                    var popform = new YBA.Plugin.popform({
                        title: "追加空间",
                        className: "ui-dialog-addToSpace",
                        content: YBA.Common.ysmart(Biz.vars.tpl.addToSpaceSizeTpl, {} ),
                        width: 564,
                        destroy: true,
                        onHide: function () {
                            // 隐藏弹窗时要执行的回调函数
                        },
                        onShow: function () {
                            // 显示弹窗时要执行的回调函数
                            var op = $(".form-group");
                            var form = $(".ui-dialog-form");
                            op.each(function() {
                                var t = $(this),
                                    input = t.find(".required"),
                                    name = input.attr("name"),
                                    holder = input.siblings(".message");
                                input.blur(function() {
                                    Biz.fn.formCheck(form,name);
                                }).focus(function() {
                                    holder.show();
                                });;
                            });
                            $("#j-dataId").val(id);
                        	Biz.fn.getUserSpace(function(json){
                        		$("#j-addToSpaceSize").attr("data-maxSize",json.availableSpaceSize)
                                form.find(".message").children("i").html("您可分配空间为"+json.availableSpaceSize+"G");
                        	})
                        },
                        btns: [{
                            value: "确定",
                            className: "blue btn g-mr10",
                            fn: function () {
                                var form = $(".ui-dialog-form");
                                if (!Biz.fn.formCheck(form,"spaceSize")) {
                                    return false;
                                }else{
                                    var form = popform.self.find("form");
                                    var data = form.serialize();
                                    YBA.Data.User.addToSpaceSize(data, function(json){
                                        if(json.code == 200) {
                                            YBA.Plugin.msgtip({type: "o", msg: json.desc});
                                            popform.hide();
                                            Biz.fn.getList();
                                        }else{
                                            YBA.Plugin.msgtip({type: "i", msg: json.desc});
                                        }
                                    });
                                }
                            }
                        }, {
                            value: "取消",
                            className: "red btn g-ml10",
                            fn: function () {
                                popform.hide();
                            }
                        }]
                    }).show();

                    // 创建组织机构下拉框
                    var deptSelect = YBA.Logic.Department.deptSelect({
                        con: popform.self.find(".j-deptSelect"),
                        onchange: function(val, text){

                        }
                    });

                    return false;
                },
                //获取CA列表
                getCaList:function(dom){
                    YBA.Data.Terminal.getCaList({}, function(json){
                        if(json.code == 200) {
                            var str = "";
                            for(var i in json.cas){
                                str+="<option value='"+json.cas[i].labId+"'>"+json.cas[i].caId+"　"+json.cas[i].labTypeMap[json.cas[i].labType]+"</option>";
                            }
                            dom.html(str);
                        }
                    });
                },
                // 获取可分配空间
                getUserSpace: function(callback){
                    YBA.Data.User.getUserSpace({}, function(json){
                        if(json.code == 200) {
                            callback && callback(json);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    })
                },
                // 获取用户详情
                getUserDetail: function(id, callback){
                    YBA.Data.User.getUserDetail({userId: id}, function(json){
                        if(json.code == 200) {
                            callback && callback(json.obj);
                        }else{
                            YBA.Plugin.msgtip({type: "i", msg: json.desc})
                        }
                    })
                }
            },
            // 外部接口
            api: {
                // 设置部门id，并执行搜索
                setDepartId: function(id){
                    Biz.vars.searchVar.departId = id;
                    Biz.vars.searchVar.startPos = 1;
                    Biz.vars.pageCtrl.setPageIndex(1);
                    Biz.fn.getList();
                }
            },
            // 初始化时执行的所有事件
            event: {
                // 搜索
                search: function () {
                    // 点击“查询”时，设置搜索条件
                    Biz.el.body.delegate(".j-search", "click", function () {
                        Biz.vars.searchVar.departId = Biz.el.jdepartId.val();
                        Biz.vars.searchVar.mobile = Biz.el.jmobile.val();
                        Biz.vars.searchVar.name = Biz.el.jname.val();
                        Biz.vars.searchVar.username = Biz.el.jusername.val();
                        Biz.vars.searchVar.startPos = 1;

                        Biz.vars.pageCtrl.setPageIndex(1);

                        Biz.fn.getList();
                    });

                    // 点击“重置”时，重置搜索条件
                    Biz.el.body.delegate(".j-reset", "click", function () {
                        Biz.el.jdepartId.val("");
                        Biz.el.jdepartIdStr.val("");
                        Biz.el.jmobile.val("");
                        Biz.el.jname.val("");
                        Biz.el.jusername.val("");

                        Biz.vars.searchVar.departId = "";
                        Biz.vars.searchVar.mobile = "";
                        Biz.vars.searchVar.name = "";
                        Biz.vars.searchVar.username = "";
                        Biz.vars.searchVar.startPos = 1;

                        Biz.vars.pageCtrl.setPageIndex(1);

                        Biz.fn.getList();
                    });
                },
                //初始化搜索组织机构下拉框
                depSelect:function(){
                    YBA.Logic.Department.deptSelect({
                        con: $("#j-search-deptSelect"),
                        allOn:true,
                        onchange: function(val, text){

                        }
                    });
                },
                // 分页
                pageNav: function () {
                    // 创建分页控件
                    Biz.vars.pageCtrl = new YBA.Plugin.pageNav({
                        // 放置分页控件的容器
                        pageCon: Biz.el.jpage,
                        // 每页数量
                        pageSize: Biz.vars.searchVar.pageSize,
                        // 总数量
                        totalNum: Biz.vars.totalNum,
                        // 回调函数
                        callback: function (pageIndex) {
                            // 设置页次
                            Biz.vars.searchVar.startPos = pageIndex;
                            // 执行搜索
                            Biz.fn.getList();
                        }
                    });
                },
                // 新增用户
                addUser: function(){
                    Biz.el.jaddUser.bind("click", function(){
                        Biz.fn.userForm();
                    });
                },
                // 追加空间
                addToSpaceSize: function(){
                    Biz.el.jlist.delegate(".j-addToSpaceSize", "click", function(){
                    	var t = $(this), tr = t.closest("tr"), id = tr.attr("data-id");
                        Biz.fn.addToSpaceForm(id);
                    });
                },
                // 管理用户
                editUser: function(){
                    Biz.el.jlist.delegate(".j-editUser", "click", function(){
                        var t = $(this), tr = t.closest("tr"), id = tr.attr("data-id");
                        Biz.fn.getUserDetail(id, function(data){
                            Biz.fn.userForm(data);
                        });
                    });
                },
                // 用户批量转移
                transferUser: function(){
                    Biz.el.jtransferUser.bind("click", function(){
                        var userIdStr = "";
                        var data = {};
                        $(".j-checkEach").each(function(){
                            var t = $(this);
                            if(t.is(':checked')){
                                var tr = t.closest("tr"), id = tr.attr("data-id");
                                if(userIdStr == ""){
                                    userIdStr = id
                                }else{
                                    userIdStr = userIdStr+","+id;
                                }
                            }
                        });
                        if(userIdStr == ""){
                            YBA.Plugin.msgtip({type: "i", msg: "没有选中项！"})
                            return false;
                        }
                        data = {
                            "userIdStr":userIdStr
                        }
                        Biz.fn.userTransfer(data);
                    });
                },
                //查看用户信息
                watchUser:function(){
                    Biz.el.jlist.delegate(".j-watchUser", "click", function(){
                        var t = $(this), tr = t.closest("tr"), id = tr.attr("data-id");
                        Biz.fn.getUserDetail(id, function(data){
                            Biz.fn.userInfo(data);
                        });
                    });
                },
                //复选框全选
                checkAll:function(){
                    YBA.Plugin.checkAll({
                        allObj:Biz.el.jallObj,
                        eachObj:$(".j-checkEach"),
                        list:$("#j-list")
                    })
                }
            }
        };

        Biz.init();

        return Biz;
    }
});
